package server

import (
	"errors"
	"gitee.com/enjoy_5/spikes-rpc/internal/model"
	pb "gitee.com/enjoy_5/spikes-rpc/proto/spikes"
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"github.com/google/uuid"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func CreateSpikesOrders(in *pb.CreateSpikesOrderRequest) (info *pb.OrderInfo, err error) {
	s := model.SpikesGoodsSku{}
	first, _ := s.SpokesStockDetail(in.GoodsID, in.SpikesActivityID) //查询库存是否充足
	if first.SpikesStock < in.Num {
		return nil, errors.New("库存不足")
	}
	sum := first.SpikesPrice * float64(in.Num) //计算秒杀价格
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error { //开启一个事务
			//调用扣减秒杀库存
			s = model.SpikesGoodsSku{
				SkuID:       in.GoodsID,
				SpikesID:    in.SpikesActivityID,
				SpikesStock: in.Num,
			}
			err = s.UpdateSpokesStock(tx)
			if err != nil {
				return errors.New("扣减库存失败") //回滚
			}
			orderOn := uuid.NewString() + strconv.Itoa(int(time.Now().Unix())) //创建秒杀订单编号
			o := model.Order{
				OrderOn:       orderOn,
				GoodsID:       in.GoodsID,
				UserID:        in.UserID,
				Num:           in.Num,
				Price:         sum,
				PaymentMethod: in.PaymentMethod,
			}
			res, err := o.CreateOrder(tx) //调用订单创建
			if err != nil {
				return errors.New("订单创建失败") //回滚
			}
			price := decimal.NewFromFloat(res.Price).StringFixed(2)
			info = &pb.OrderInfo{
				OrderOn:       res.OrderOn,
				GoodsID:       res.GoodsID,
				UserID:        res.UserID,
				Num:           res.Num,
				Price:         price,
				PaymentMethod: res.PaymentMethod,
				PaymentStatus: res.PaymentStatus,
				OrderStatus:   res.OrderStatus,
			}
			return nil
		})
	})
}

// 删除秒杀活动
func DeleteOrder(in *pb.DeleteSpikesOrderRequest) error {
	s := model.Order{
		Model: gorm.Model{
			ID: uint(in.OrderID),
		},
	}
	err := s.GetOrderByOrderID()
	if err != nil {
		return errors.New("订单不存在")
	}
	return s.DeleteOrderByOrderID()
}
